package com.ea.report.schedule;

import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.util.Calendar;
import java.util.Date;

/**
 * @author SunYuXin
 * @className: com.ea.report.schedule
 * @Description: 定时任务处理内存问题
 * @date 2025/1/2 23:45
 */
@Component
@EnableScheduling
@Slf4j
public class MemorySchedule {

    @Scheduled(cron = "0 0 4 * * ?")
    public void deleteVideoForWeek(){
        String path="/maven/upload/user/video";
        deleteVideoForWeekImpl(path);
    }

    public void deleteVideoForWeekImpl(String path){
        //获取一天前的时间戳
        Date date1 = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date1);
        calendar.add(Calendar.DATE, -0);
        Date date2 = calendar.getTime();
        long t1 = date2.getTime();

        try {
            File f = new File(path);
            File[] files = f.listFiles();
            for (int i = 0; i < files.length; i++) {

                //获取文件最后一次被修改的时间
                String filePath = files[i].getCanonicalPath();
                Long lastTime = files[i].lastModified();

                if (lastTime < t1) {
                    //直接删除文件，递归删除目录
                    if (files[i].exists() && (files[i].isFile()||files[i].isDirectory()))
                    {
                        File file = new File(filePath);
                        if(file.isFile()){
                            file.delete();
                        }
                        if(file.isDirectory()) {
                            deleteDir(filePath);
                            file.delete();
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public  void deleteDir(String path){

        File file = new File(path);
        File[] list = file.listFiles();
        for(File f:list){
            if(f.isDirectory()){
                deleteDir(f.getPath());
                f.delete();
            }else{
                f.delete();
            }
        }
    }
}
